﻿
using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Mvc;

using WebResource.ApiModels;

namespace WebResource
{
    [ApiController]//记住这个单词
    [Route("webresources/LocalFile")]//记住这个
    public class LocalFileServer : GCCAPIControllerBase
    {
        public LocalFileServer(AbsGCCContext context) : base(context)
        {
        }

        [HttpGet("items")]
        public DataResponse<GetLocalFileItemsResponse> GetAllItems([FromQuery] GetLocalFileItemsRequest request)
        {
            if (!LocalFileManager.Instance.IsLocalFolderPath(request.Path))
            {
                return IllegalRequest<GetLocalFileItemsResponse>();
            }
            var res = new GetLocalFileItemsResponse();

            {
                var items = LocalFileManager.Instance.GetFiles(request.Path);

                foreach (var item in items)
                {
                    var temp = new FileInfo(item);
                    res.Files.Add(new GetLocalFileItemsResponse.FileItemInfo()
                    {
                        FileName = temp.Name,
                        Size = temp.Length
                    });
                }
            }
            {
                var items = LocalFileManager.Instance.GetFolders(request.Path);

                foreach (var item in items)
                {
                    var temp = new DirectoryInfo(item);
                    res.Folders.Add(new GetLocalFileItemsResponse.FolderInfo()
                    {
                        FolderName = temp.Name,
                    });
                }
            }

            return HandleData(res);
        }


        [HttpGet("items/path")]
        public ActionResult GetLocalFile([FromQuery] string path, [FromQuery] string mimeType = "application/octet-stream")
        {
            if (!LocalFileManager.Instance.CheckFilePath(path, out var validPath))
            {

                return new EmptyResult();
            }
            var fs = System.IO.File.OpenRead(validPath);
            FileStreamResult fsr = new FileStreamResult(fs, mimeType);
            if (mimeType == "application/octet-stream")
            {
                fsr.FileDownloadName = new FileInfo(validPath).Name;
            }
            return fsr;
        }

    }
}
